﻿using LandingPagesStats.Data;
using LandingPagesStats.Models;
using LandingPagesStats.WebAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace LandingPagesStats.WebAPI.Controllers
{
    public class HostsController : BaseApiController
    {
        [HttpGet]
        public IQueryable<HostModel> GetAll()
        {
            return this.ExecuteOperationAndHandleExceptions(() =>
            {
                var context = new LandingPagesStatsDbContext();
                var hosts = (from host in context.Hosts
                             select new HostModel()
                             {
                                 HostId = host.HostId,
                                 Url = host.Url,
                                 LastEntry = host.LastEntry,
                                 Count = host.Count

                             }).AsQueryable();

                return hosts;
            });
        }

        [HttpPost]
        public void RegisterUser(HostUrlModel model)
        {
            var context = new LandingPagesStatsDbContext();
            var host = GetHostByUrl(model, context);

            if (host != null)
            {
                host.LastEntry = DateTime.Now;
                host.Count++;
            }
            else
            {
                host = new Host()
                {
                    Count = 1,
                    Url = model.Source.ToLower(),
                    LastEntry = DateTime.Now
                };

                context.Hosts.Add(host);
            }

            context.SaveChanges();
        }

        private Host GetHostByUrl(HostUrlModel model, LandingPagesStatsDbContext context)
        {
            var hostnameToLower = model.Source.ToLower();
            var dbUser = context.Hosts.FirstOrDefault(u => u.Url == hostnameToLower);
            return dbUser;
        }
    }
}
